# _*_ coding:utf-8 _*_
# @Time  : 2023.08.24
# @Author: zizlee
import pathlib

from fastapi import APIRouter, Query, HTTPException
from db_utils import BaseDatabaseConnection
from pydantic import BaseModel
from utils import datetime_utils
from response import APIResponse
from .doctor_tools import report_temp_files, ExDoctorDatabase, FundReconciler


class AccountApi:
    def __init__(self, fn: str, start: str, end: str):
        self.fn = fn
        self.start = datetime_utils.auth_yyyy_mm_dd(start, obj=True)
        self.end = datetime_utils.auth_yyyy_mm_dd(end, obj=True)
        if not self.start:
            raise HTTPException(status_code=422, detail='query参数`start`格式错误,接受yyyy-mm-dd类型')
        if not self.end:
            raise HTTPException(status_code=422, detail='query参数`end`格式错误,接受yyyy-mm-dd类型')
        self.start_integer = self.start.strftime('%Y%m%d')
        self.end_integer = self.end.strftime('%Y%m%d')

    def account_overview(self):
        database = ExDoctorDatabase(fund_num=self.fn, start=self.start_integer, end=self.end_integer)
        fund_list = database.query_fund_data()
        # !很重要! 重置诊断缓存情况
        report_temp_files(prefix=self.fn, start=self.start_integer, end=self.end_integer, clear=True)

        if len(fund_list) < 1:
            data = {'overview': []}
        else:
            fund_reconciler = FundReconciler(fund_list)
            data = fund_reconciler.account_overview(filename_prefix=self.fn, doc=True)
        return APIResponse.success(data=data)

    def account_net_value(self):
        database = ExDoctorDatabase(fund_num=self.fn, start=self.start_integer, end=self.end_integer)
        fund_list = database.query_fund_data()
        if len(fund_list) < 1:
            data = {'cum_net_profit': '', 'cum_net_pullback': '', 'net_value_volatility': ''}
        else:
            fund_reconciler = FundReconciler(fund_list)
            # 累计净值与累计净利润图-文字
            cum_net_value_profit = fund_reconciler.create_cum_net_value_cum_profit(filename_prefix=self.fn, fig_size=(5.5, 3.75), xtick_count=12)
            # 累计净值与最大回撤
            cum_net_pullback = fund_reconciler.create_value_pullback(filename_prefix=self.fn, fig_size=(5.5, 3.75), xtick_count=12)
            # 当日净值与波动率
            net_value_volatility = fund_reconciler.create_day_net_value_volatility(filename_prefix=self.fn, fig_size=(5.5, 3.75), xtick_count=12)
            data = {
                'cum_net_profit': cum_net_value_profit,
                'cum_net_pullback': cum_net_pullback,
                'net_value_volatility': net_value_volatility
            }
        return APIResponse.success(data=data)

    def account_period_profit(self):
        database = ExDoctorDatabase(fund_num=self.fn, start=self.start_integer, end=self.end_integer)
        fund_list = database.query_fund_data()
        if len(fund_list) < 1:
            data = {
                'daily_txt': '',
                'daily_img': '',
                'week_txt': '',
                'week_img': '',
                'month_txt': '',
                'month_img': ''
            }
        else:
            fund_reconciler = FundReconciler(fund_list)
            data = fund_reconciler.create_period_profit(filename_prefix=self.fn, fig_size=(5.5, 3.75), xtick_count=12)
        return APIResponse.success(data=data)


ex_account_api = APIRouter()


@ex_account_api.get('/overview/')  # 账户概览
def account_overview(fn: str = Query(...), start: str = Query(...), end: str = Query(...)):
    return AccountApi(fn=fn, start=start, end=end).account_overview()


@ex_account_api.get('/netValue/')  # 账户净值分析
def account_net_value(fn: str = Query(...), start: str = Query(...), end: str = Query(...)):
    return AccountApi(fn=fn, start=start, end=end).account_net_value()


@ex_account_api.get('/periodProfit/')  # 周期盈亏分析
def account_period_profit(fn: str = Query(...), start: str = Query(...), end: str = Query(...)):
    return AccountApi(fn=fn, start=start, end=end).account_period_profit()
